package servlet;

import bean.User;
import com.alibaba.fastjson.JSON;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
            request.setCharacterEncoding("utf-8");// 设置请求参数的编码格式
            response.setContentType("text/json;charset=utf-8");// 设置网页界面相应的代码
            String line = request.getReader().readLine();
            User user = JSON.parseObject(line, User.class);//拿到键值对
            UserService service = new UserService();
            User user2 = service.login(user.getUsername(), user.getPsw());
            System.out.println(user2);
            if (user2 != null) {
                HttpSession session = request.getSession();
                session.setAttribute("user_id", user2.getId());
                session.setAttribute("isManager", user2.getIsManager());

                if ("1".equals(user2.getIsManager())) {
                    response.getWriter().write("11"); //管理员
                } else {
                    response.getWriter().write("10"); //普通用户
                }

            } else {
                response.getWriter().write("00");//账号密码错误
            }
        }
//        else {
//            response.getWriter().write("12");
//        }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
            this.doPost(request, response);
    }
}
